
module mul_conj(clk,cal_en,
		R,I,
		sR,sI,
		z,zi,
		rdy
    );
input clk,cal_en;
input [15:0] R,I;//FLOW:A
input [15:0] sR,sI;//STS:B
output [31:0] z,zi;
output rdy;

reg signed [16:0]sumB,sumA;//Br+Bi,Ar+Ai,Br-Bi
reg  signed [16:0]minusB;
reg  signed [15:0] R_r,I_r,sR_r;
reg times_en;

always @(posedge clk) begin
	if(cal_en) begin
		sumB<=$signed(sR)+$signed(sI);
		sumA<=$signed(R)+$signed(I);
		minusB<=$signed(sR)-$signed(sI);
		R_r<=$signed(R);
		I_r<=$signed(I);
		sR_r<=$signed(sR);		
		times_en<=1;
	end
	else begin
		times_en<=0;
		sumB<='b0;
		sumA<='b0;
		minusB<='b0;
		R_r<='b0;
        I_r<='b0;
        sR_r<='b0;
	end
end

wire  signed [16:0] sb,sa,m1;
wire  signed [15:0] r1,i1,sr1;
wire t_en;
assign sb = sumB;
assign sa = sumA;
assign m1 = minusB;
assign t_en = times_en;
assign r1 = R_r;
assign i1 = I_r;
assign sr1 = sR_r;

wire  [32:0] timesArsumB,timesBrsumA;//Ar(Br+Bi),Ai(Br-Bi),Br(Ar+Ai)
wire  [32:0] timesAiminusB;
reg glue_en1,glue_en2,glue_en3;

mult_ele arsb(clk, sb,r1, t_en, timesArsumB);
mult_ele brsa(clk,sa,sr1,t_en,timesBrsumA);
mult_ele aimb(clk,m1,i1,t_en,timesAiminusB);

always @(posedge clk) begin
	if(times_en) begin
		//timesArsumB<=$signed(R_r) * sumB;
		glue_en1 <=1;
	end
	else begin
		glue_en1<=0;
		//timesArsumB<='b0;
	end
end

always @(posedge clk) begin
	if(times_en) begin
		//timesAiminusB<=$signed(I_r) * minusB;
		glue_en2 <=1;
	end
	else begin
		glue_en2<=0;
		//timesAiminusB<='b0;
	end
end

always @(posedge clk) begin
	if(times_en) begin
		//timesBrsumA<=$signed(sR_r) * sumA;
		glue_en3 <=1;
	end
	else begin
		glue_en3<=0;
		//timesBrsumA<='b0;
	end
end


reg signed [33:0] tempZR,tempZI;//Zr,Zi 
reg Z_en;

always @(posedge clk) begin
	if(glue_en1 & glue_en2 & glue_en3) begin
		tempZR<= $signed(timesBrsumA)-$signed(timesAiminusB);
		tempZI<= $signed(timesBrsumA)-$signed(timesArsumB);
		Z_en<=1;		
	end
	else begin
		Z_en<=0;
		tempZR<='b0;
		tempZI<='b0;
	end
end

reg [31:0] Z_R,Z_I;//getting rid of headers
reg RD;
always @(posedge clk) begin
	if(Z_en) begin
		Z_R<=$unsigned({tempZR[33],tempZR[30:0]});
		Z_I<=$unsigned({tempZI[33],tempZI[30:0]});
		RD<=1;
	end
	else begin
		RD<=0;
		Z_R<='b0;
		Z_I<='b0;
	end
end

assign z=Z_R;
assign zi=Z_I;
assign rdy=RD;
endmodule